import { UserConfigExport, ConfigEnv, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
//引入SVG需要用到的插件
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import { viteMockServe } from "vite-plugin-mock";
export default ({ command, mode }: ConfigEnv): UserConfigExport => {
  //获取各种环境下的对应的变量
  let env = loadEnv(mode, process.cwd());
  return {
    plugins: [
      vue(),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
        svgoOptions: true,
        symbolId: "icon-[dir]-[name]",
      }),
      viteMockServe({
        // default
        mockPath: "mock",
        localEnabled: command === "serve",
      }),
    ],
    resolve: {
      alias: {
        "@": path.resolve("./src"), //相对路径别名配置，使用@代替src
      },
    },
    //scss全局变量配置
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/variable.scss";',
        },
      },
    },
    build: {
      rollupOptions: {
        output: {
          entryFileNames: "js/[name]-[hash].js", // 指定 JS 文件的输出路径及命名规则
          chunkFileNames: "js/[name]-[hash].js", // 指定分片文件的输出路径及命名规则
          assetFileNames: (assetInfo: any) => {
            // 设置不同类型文件的输出路径及命名规则
            if (
              assetInfo.type === "asset" &&
              /\.(jpe?g|png|gif|svg)$/i.test(assetInfo.name)
            ) {
              return "img/[name].[hash].[ext]"; // 图像文件输出路径及命名规则
            }
            if (
              assetInfo.type === "asset" &&
              /\.(ttf|woff|woff2|eot)$/i.test(assetInfo.name)
            ) {
              return "fonts/[name].[hash].[ext]"; // 字体文件输出路径及命名规则
            }
            return "[ext]/name1-[hash].[ext]"; // 其他资源文件输出路径及命名规则
          },
        },
      },
    },
    //代理跨越
    server: {
      port: 8090,
      proxy: {
        [env.VITE_APP_BASE_API]: {
          //获取数据的服务器地址设置
          target: env.VITE_SERVER,
          //需要代理跨域
          changeOrigin: true,
          //路径重写
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
  };
};
